/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */
package com.ykht.proj.coupon.service.impl;
import java.time.LocalDateTime;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.CommentStatusEnum;
import com.ykht.proj.coupon.entity.*;
import com.ykht.proj.coupon.mapper.FxCmsInfoMapper;
import com.ykht.proj.coupon.mapper.FxCommentMapper;
import com.ykht.proj.coupon.service.CnPersonService;
import com.ykht.proj.coupon.service.FxCommentService;
import com.ykht.proj.coupon.vo.FxCommentVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.ykht.proj.coupon.service.FxCommentUpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 资讯评价表
 *
 * @author proj code generator
 * @date 2021-07-07 16:20:00
 */
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class FxCommentServiceImpl extends ServiceImpl<FxCommentMapper, FxComment> implements FxCommentService {

	private final FxCommentMapper fxCommentMapper;
	private final FxCmsInfoMapper fxCmsInfoMapper;
	private final CnPersonService cnPersonService;
	private final FxCommentUpService fxCommentUpService;

	/**
	 * 资讯评价表 分页查询
	 *
	 * @param page        分页对象
	 * @param fxCommentVo 资讯评价表
	 * @return
	 */
	@Override
	public IPage<FxCommentVo> getFxCommentPage(Page page, FxCommentVo fxCommentVo) {
		return fxCommentMapper.getFxCommentPage(page, fxCommentVo);
	}

	/**
	 * pc 审核评论
	 *
	 * @param fxCommentVo 资讯评价表
	 * @return R
	 */
	@Override
	public void updateFxComment(FxCommentVo fxCommentVo) {
		this.updateById(BeanUtil.toBean(fxCommentVo, FxComment.class));
		if (fxCommentVo.getStatus().equals(CommentStatusEnum.AT_WORK.getValue())){
			fxCmsInfoMapper.updateStatisticsByCmsId(fxCommentVo.getCmsId(),0, 0, 0, 1, 0);
		} else if (fxCommentVo.getStatus().equals(CommentStatusEnum.BE_OVERDUE.getValue())
				&& fxCommentVo.getOriginalStatus().equals(CommentStatusEnum.AT_WORK.getValue())){
			fxCmsInfoMapper.updateStatisticsByCmsId(fxCommentVo.getCmsId(),0, 0, 0, -1, 0);
		}
	}


	@Override
	public R<Page<CommentVO4C>> showPage(Page<FxComment> page, Long cmsId) {
		Page<CommentVO4C> cPage = new Page<>();
		List<CommentVO4C> list = new ArrayList<>();
		page = this.page(page,Wrappers.lambdaQuery(FxComment.class)
				.eq(FxComment::getCmsId,cmsId)
				.and(o->o.eq(FxComment::getStatus,0).or(oo->oo.eq(FxComment::getPublishId,SecurityUtils.getPersonId()).eq(FxComment::getStatus,1)))
				.orderByDesc(FxComment::getUpTimes).orderByDesc(FxComment::getCreateTime));

		page.getRecords().stream().forEach(o->list.add(BeanUtil.toBean(o,CommentVO4C.class)));

//		Set<Long> pubIds = new HashSet<>();//发布人ids
		Set<Long> commetIds = new HashSet<>();//评论ids
		page.getRecords().stream().forEach(o->{
//			pubIds.add(o.getPublishId());
			commetIds.add(o.getId());
		});
		if (commetIds.size()>0){
//			Map<Long, String> pubMap = cnPersonService.listByIds(pubIds).stream().collect(Collectors.toMap(CnPerson::getId, CnPerson::getHeadPortrait));
			Map<Long, List<Long>> upMap = fxCommentUpService.list(Wrappers.lambdaQuery(FxCommentUp.class).in(FxCommentUp::getCommentId,commetIds))
					.stream().collect(Collectors.groupingBy(FxCommentUp::getCommentId, Collectors.mapping(FxCommentUp::getPerId, Collectors.toList())));
			list.stream().forEach(o->{
//				o.setPublishPic(pubMap.get(o.getPublishId()));
				//是否点赞
				List<Long> upList = upMap.getOrDefault(o.getId(),new ArrayList<Long>());
				boolean b = upList.stream().anyMatch(oo -> oo.equals(SecurityUtils.getPersonId()));
				o.setUpFlag(b?1:0);
			});
		}
		cPage.setRecords(list);
		cPage.setSize(page.getSize());
		cPage.setTotal(page.getTotal());
		cPage.setCurrent(page.getCurrent());
		return R.ok(cPage);
	}

	@Override
	public R publish(FxComment fxComment) {

		if (StringUtils.isEmpty(fxComment.getContent())) return R.failed("评论为空");
		List<FxSensitiveWords> list = new FxSensitiveWords().selectList(Wrappers.lambdaQuery(FxSensitiveWords.class).select(FxSensitiveWords::getContent).eq(FxSensitiveWords::getStatus, 0));
		List<String> collect = list.stream().filter(o -> fxComment.getContent().replaceAll(" ", "").contains(o.getContent())).map(FxSensitiveWords::getContent).collect(Collectors.toList());

		boolean b = collect.size()>0;
		String s = collect.stream().collect(Collectors.joining(",", "触发敏感词:[", "]"));
		FxCmsInfo cmsInfo = new FxCmsInfo().selectById(fxComment.getCmsId());
		fxComment.setCompanyId(cmsInfo.getCompanyId());
		fxComment.setBrandId(cmsInfo.getBrandId());
		fxComment.setCmsId(cmsInfo.getId());
		fxComment.setPublishId(SecurityUtils.getPersonId());
		fxComment.setUpTimes(0);
		fxComment.setPublishName(SecurityUtils.getPerson().getNickName());
		fxComment.setPublishPic(SecurityUtils.getPerson().getHeadPortrait());
		fxComment.setStatus(b?2:1);
		fxComment.setReason(b?s:null);
		fxComment.setApprovalDate(b?LocalDateTime.now():null);
		fxComment.setCreateUser(SecurityUtils.getPersonId());
		fxComment.setCreateTime(LocalDateTime.now());
		fxComment.insert();
		return b?R.failed("存在敏感词汇"):R.ok(fxComment);
	}
}
